/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : pop_fix.js
*  Description  : my 지역설정 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-05-08  김효순    Created.  
*  2012-05-08  김효순    Complete.  
*******************************************************************************/

jQuery(function($){
	// 지역선택
	function clsAreaGolfList()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"_NOVALUE": "코스를 선택해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsAreaGolfList.prototype = {
		_init: function(){
			var $layer = $("div.pw_area dl.pop_area_choice");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("label:first").clone(true)
			}
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setLayer: function($newLayer){
			var $layer = this.$getLayer();
			
			$layer.empty();
			$layer.append($newLayer.html());
			
			$layer.find("input:checkbox").prop("checked", false);
		}
		, setMyConfig: function(thisData){
			var $layer = this.$getLayer();
			
			for(var i=0;i<thisData.length;i++){
				var $obj = $layer.find("input:checkbox[value='" + thisData[i]["지역코드"] + "," + thisData[i]["골프장코드"] + "']");
				$obj.prop("checked", true);
			}
			
			this.checkcheck();
		}
		, getValue: function(){
			var $layer = this.$getLayer();
			var szRet = "";
			
			$layer.find(":checkbox:checked").filter(function(){
				if($(this).parent().parent().get(0).tagName.toUpperCase() == "DD") return true;
				else return false;
			}).each(function(){
				if(szRet) szRet += ",";
				szRet += $(this).val()+",_NOT";
			});
			
			return szRet;
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			
			$layer.hide();
			if($layer.parent().find("div#tmpSpin").length == 0){
				$layer.parent().prepend("<div id='tmpSpin' style='position:absolute; width:160px; height:150px;' />");
			}
			$layer.parent().find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.parent().find("div#tmpSpin").hide().spin(false);
			$layer.show();
		}
		, checkcheck: function(){
			var $layer = this.$getLayer();
			
			$layer.find("dd").each(function(){
				var a = $(this).find("input:checkbox").length;
				var b = $(this).find("input:checkbox:checked").length;
				
				var $p = $(this).prev("dt").find("input:checkbox");
				$p.prop("checked", Boolean(a && a == b));
			});
			
			var a = $layer.find("dt:gt(0) input:checkbox").length;
			var b = $layer.find("dt:gt(0) input:checkbox:checked").length;
			$layer.find("dt:eq(0) input:checkbox").prop("checked", Boolean(a && a==b));
		}
		, getError: function(){
			if(this.errMsg) return this._ERRMSG[this.errMsg];
			else return null;
		}
		, valid: function(){
			var $layer = this.$getLayer();
			
			if(!$layer.find("input:checkbox:checked").length){
				this.errMsg = "_NOVALUE";
				return false;
			}
			
			return true;
		}
	}
	
	function clsComm()
	{
		
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			
		}
		// 나의 설정
		, getMyConfig: function(arg){
			var thisClass = this;
			
			arg = arg || {};
			arg["콜백"] = arg["콜백"] || function(){};
			
			//ajax
			var serviceName = "reservMyOption";
			document.objGlobal.ajax({
				"sid": "RS001"
				, "servicename": serviceName
			}, {
				
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
					, "결과값": []
				}
				
				var items = ret["msp"]["contents"]["items"];
				
				if(items){
					if(!items.length) items = new Array(items);
					
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						res["결과값"].push({
							"지역코드": _util.nvl(obj["region"])
							, "골프장코드": _util.nvl(obj["golfclub__id"])
						});
					}
				}
				arg["콜백"].apply(null, [res]);
			});
		}
		// 설정 저장
		, myConfigSubmit: function(arg){
			var thisClass = this;
			
			arg = arg || {};
			arg["콜백"] = arg["콜백"] || function(){};
			
			//ajax
			var serviceName = "regReservMyOption";
			document.objGlobal.ajax({
				"sid": "RS001"
				, "servicename": serviceName
			}, {
				"search": arg["코드조합"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
	}
	
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objAreaGolfList = null;
		
		this.openerControl = null;
		
		this._permitStart = null;
		
		this._init();
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objAreaGolfList = new clsAreaGolfList();
			
			this._bind();
			this._beforeStart();
			
			_util.setWindowSize();
		}
		, _preload: function(){
			_gf.spinStart();
			
			if(opener){
				this.openerControl = opener.document.objControl;
			}
			
			if(!this.openerControl){
				self.close();
				return;
			}
		}
		, _beforeStart: function(){
			var thisClass = this;
			
			this._permitStart = {
			
			}
			
			// 관심지역 레이어
			this.objAreaGolfList.setLayer(this.openerControl.$getAreaGolfListLayer());
			
			// 내설정
			this.objComm.getMyConfig({
				"콜백": function(ret){
					thisClass.objAreaGolfList.setMyConfig(ret["결과값"]);
				}
			});
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return true;
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			// 지역선택 체크박스
			this.objAreaGolfList.$getLayer().on("click", "input:checkbox", function(){
					var $p = $(this).parent().parent();
					
					switch($p.get(0).tagName.toUpperCase()){
						case "DD":
							thisClass.objAreaGolfList.checkcheck();
							break;
						case "DT":
							var n = thisClass.objAreaGolfList.$getLayer().find("input:checkbox").index($(this));
							var v = $(this).prop("checked");
							
							if(n === 0){
								thisClass.objAreaGolfList.$getLayer().find("input:checkbox:gt(0)").prop("checked", v);
							}else{
								var $n = $p.next("dd");
								$n.find("input:checkbox").prop("checked", v);
							}
							break;
					}
			});
			
			$(document).on("click", "img[alt='MY설정완료'], img[alt='close']", function(){
				var alt = $(this).attr("alt");
				
				switch(alt){
					case "MY설정완료":
						if(!thisClass.objAreaGolfList.valid()){
							alert(thisClass.objAreaGolfList.getError());
							return;
						}
						
						document.objGlobal.spinStart("sending...");
						thisClass.objComm.myConfigSubmit({
							"코드조합": thisClass.objAreaGolfList.getValue()
							, "콜백": function(ret){
								thisClass.finishMyConfigSubmit(ret);
							}
						});
						break;
					case "close":
						self.close();
						break;
				}
			});
		}
		, _start: function(){
			
		}
		// 설정 저장 완료
		, finishMyConfigSubmit: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(!ret["결과코드"] != "00000") return;
			
			_gf.spinEnd();
			
			this.openerControl.closeMySetting(self);
			
			self.close();
		}
	}
	
	document.objControl = new clsControl();
});